package com.example.hotelapp.Activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.hotelapp.Base.BaseActivity;
import com.example.hotelapp.Bean.UserLoginBean;
import com.example.hotelapp.Bean.UserRegisterBean;
import com.example.hotelapp.R;
import com.example.hotelapp.Utils.AppNetConfig;
import com.google.gson.Gson;
import com.kongzue.dialog.v2.WaitDialog;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static com.example.hotelapp.Utils.MyCommonUtils.ToastShow;
import static com.example.hotelapp.Utils.MyCommonUtils.checkPhoneValid;
import static com.example.utils.CommonUtils.IntentToPage;
import static com.example.utils.CommonUtils.OKPostValue;
import static com.example.utils.CommonUtils.SaveInfo;
import static com.example.utils.CommonUtils.setSystemBarColor;


/**
 * 登录页
 */
public class LoginActivity extends BaseActivity {

//    找到view对象，View注入框架（添加至第三方开源框架）
    @BindView(R.id.name)
    EditText name;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.yzm)
    TextView yzm;
    @BindView(R.id.wjmm)
    TextView wjmm;
    @BindView(R.id.quxiao)
    ImageView quxiao;
    @BindView(R.id.register)
    TextView register;
    private Activity activity;
    private static final int CODELOGIN = 1;//验证码登录
    private static final int FINDPWD = 2;//找回密码
    public static final int REGISTER = 3;//注册

    /**
     * 加载布局（activity_login）
     */
    @Override
    protected int setLayoutId() {
        return R.layout.activity_login;
    }

    /**
     * 初始化
     */
    @Override
    protected void init() {
        activity = this;
        login.setAlpha(0.5f);//改变整个view的透明度（0.5float）
        login.setClickable(false);//禁止点击（可以点击但是无效）
        setSystemBarColor(activity, R.color.white);//系统栏颜色
//        文本变化监听器
        name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String names = name.getText().toString().trim();
                String pwd = password.getText().toString().trim();
                if (pwd.length() > 0 && names.length() > 0) {
                    System.out.println("不是名字");
                    login.setAlpha(1.0f);
                    login.setClickable(true);
                }
            }
        });

        password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String names = name.getText().toString().trim();
                String pwd = password.getText().toString().trim();
                if (pwd.length() > 0 && names.length() > 0) {
                    login.setAlpha(1.0f);
                    login.setClickable(true);
                }
            }
        });
    }

    /**
     * 点击事件
     */
    @OnClick({R.id.login, R.id.yzm, R.id.wjmm,R.id.quxiao, R.id.register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login:
                LoginAction();
                break;
            case R.id.yzm:
                SendCodeLogin(activity, CODELOGIN);
                break;
            case R.id.wjmm:
                SendCodeLogin(activity, FINDPWD);
                break;
            case R.id.quxiao:
                System.exit(0);
                finishAffinity();
                break;
            case R.id.register:
                SendCodeLogin(activity, REGISTER);
                break;
        }
    }

    /**
     * 登录判断
     */
    private void LoginAction() {
        String names = name.getText().toString().trim();
        String pwd = password.getText().toString().trim();
        if (names.isEmpty() && pwd.isEmpty()) {
            ToastShow(activity, "请输入完整信息");
        } else if (names.length() != 11) {
            ToastShow(activity, "请输入有效的手机号");
        } else {
            WaitDialog.show(activity, "登录中...");
            OKPostValue("phone", names, "password", pwd, AppNetConfig.Login, new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    WaitDialog.dismiss();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastShow(activity, "服务器出错，请稍后再试");
                        }
                    });
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    WaitDialog.dismiss();
                    //获取返回的json数据并解析
                    String json = response.body().string();
                    System.out.println(json);
                    UserLoginBean databean = new Gson().fromJson(json, UserLoginBean.class);
                    int code = databean.getCode();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (code == 1) {
                                SaveInfo(activity,"GetPhone","phone",names);
                                SaveInfo(activity,"GetUid","id", String.valueOf(databean.getData().get(0).getId()));
                                IntentToPage(activity,MainActivity.class);
                            } else {
                                ToastShow(activity, "手机号/密码不正确");
                            }
                        }
                    });
                }
            });
        }
    }

    /**
     * 验证码登录/找回密码/新用户注册
     */
    public void SendCodeLogin(Context context, int state) {
        RegisterPage page = new RegisterPage();
        //如果使用我们的ui，没有申请模板编号的情况下需传null
        page.setTempCode(null);
        page.setRegisterCallback(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //成功回调
                    // 处理成功的结果
                    HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                    // 国家代码，如“86”
                    String country = (String) phoneMap.get("country");
                    // 手机号码，如“13800138000”
                    String phone = (String) phoneMap.get("phone");
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (state == CODELOGIN) {//验证码登录
                            SaveInfo(activity,"GetPhone","phone",phone);
                            IntentToPage(activity, MainActivity.class);//登录成功，跳转到首页
                        } else if (state == FINDPWD) {//找回密码
                            SaveInfo(activity,"GetPhone","phone",phone);
                            IntentToPage(activity, MainActivity.class);//跳转到找回密码页
                        }else if (state == REGISTER){//新用户注册
                            RegisterAction(phone);
                        }

                    }
                }
            }
        });
        page.show(context);
    }

    /**
     * 注册
     */
    private void RegisterAction(String phone) {
        WaitDialog.show(activity,"注册中...");
        OKPostValue("phone", phone,"photo","profile.jpg" , AppNetConfig.Register, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                WaitDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastShow(activity, "服务器出错，请稍后再试");
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                WaitDialog.dismiss();
                //获取返回的json数据并解析
                String json = response.body().string();
                System.out.println(json);
                UserRegisterBean databean = new Gson().fromJson(json, UserRegisterBean.class);
                int code = databean.getCode();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (code == 1) {
                            SaveInfo(activity,"GetPhone","phone",phone);
                            SaveInfo(activity,"GetUid","id", String.valueOf(databean.getData().getId()));
                            IntentToPage(activity,MainActivity.class);
                        } else {
                            ToastShow(activity,"注册失败");
                        }
                    }
                });
            }
        });
    }

}
